package com.dev118.jexample.mongodb.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dev118.jexample.mongodb.AbstractDAO;
import com.dev118.jexample.mongodb.dao.GenericDAO;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

public class GenericDAOImpl extends AbstractDAO implements GenericDAO {

	public GenericDAOImpl(DBCollection collection) {
		super(collection);
	}

	public int save(DBObject dbObj) {
		return this.collection.insert(dbObj).getN();
	}

	public int save(List<DBObject> listDBObj) {
		return this.collection.insert(listDBObj).getN();
	}

	public int remove(DBObject dbObjParams) {
		return this.collection.remove(dbObjParams).getN();
	}

	public int update(DBObject dbObjParams, DBObject newDBObjData) {
		return this.collection.update(dbObjParams, newDBObjData).getN();
	}

	public DBObject findOne(DBObject dbObjParams) {
		return this.collection.findOne(dbObjParams);
	}

	public DBObject findOne(DBObject dbObjFlds, DBObject dbObjParams) {
		return this.collection.findOne(dbObjParams, dbObjFlds);
	}

	public List<DBObject> finds(DBObject dbObjParams, DBObject dbObjSort) {
		return this.collection.find(dbObjParams).sort(dbObjSort).toArray();
	}

	public List<DBObject> finds(DBObject dbObjFlds, DBObject dbObjParams,
			DBObject dbObjSort) {
		return this.collection.find(dbObjParams, dbObjFlds).sort(dbObjSort)
				.toArray();
	}

	public Long count(DBObject dbObjParams) {
		return this.collection.getCount(dbObjParams);
	}

	public Map<String, Object> page(DBObject dbObjFlds, DBObject dbObjParams,
			DBObject dbObjSort, Integer offset, Integer pageSize) {
		Long count = this.count(dbObjParams);
		List<DBObject> list = this.collection.find(dbObjParams, dbObjFlds)
				.limit(pageSize).skip(offset).sort(dbObjSort).toArray();
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("COUNT", count);
		result.put("RESULT", list);
		return result;
	}

}
